const fs = require('fs'),
    path = require("path"),
    webpack = require('webpack'),
    os = require('os'),
    merge = require('webpack-merge');

//var glob = require('glob');
//function entries (globPath) {
//    var files = glob.sync(globPath);
//    var entries = {}, entry, dirname, basename;
//
//    for (var i = 0; i < files.length; i++) {
//        entry = files[i];
//        dirname = path.dirname(entry);
//        basename = path.basename(entry, '.js');
//        entries[path.join(dirname, basename)] = './' + entry;
//    }
//
//    return entries;
//}

const PATHS = {
    js: path.join(__dirname, 'src/js/'),
    build: path.join(__dirname, 'build/public/js/'),
    assets: path.join(__dirname, 'build/public/assets')
};

const ENV = process.env.RUN_ENV || 'dev', //看 jenkins 配置
    DEV = 'dev',
    TEST = 'test',
    PRO = 'production';

const entry = {},
    setupEntry = function (srcDir) {
        var files = fs.readdirSync(srcDir),
            getFiles = function (files, prefix) {
                //遍历数组，里面有文件或目录
                files.forEach(function (file) {
                    //组件及常量不作为entry
                    if (file.indexOf('components') > -1 ||
                        file.indexOf('const') > -1 ||
                        file.indexOf('lib') > -1)
                        return;
                    
                    var i = file.indexOf('.'),
                        name = file.substr(0, i);
                    
                    var type = os.type(); //判断操作系统名称，基于linux的返回linux,基于苹果的返回Darwin,基于windows的返回Windows_NT
                    
                    //目录
                    if (i == -1) {
                        var dir = path.resolve(srcDir, file),
                            pre = type == 'Windows_NT' ?
                                dir.substr(dir.lastIndexOf('\\') + 1) :
                                dir.substr(dir.lastIndexOf('/') + 1);
                        
                        getFiles(fs.readdirSync(dir), pre);
                    }
                    //js文件
                    else if (file.indexOf('js') > -1) {
                        if (prefix) {
                            var jsFile = path.resolve(srcDir, prefix, file);
                            type == 'Windows_NT' ?
                                entry[prefix + '\\' + name] = jsFile :
                                entry[prefix + '/' + name] = jsFile;
                        }
                        else {
                            var jsFile = path.resolve(srcDir, file);
                            entry[name] = jsFile;
                        }
                    }
                    
                    
                });
            };
        getFiles(files);
        console.log(entry)
    };
setupEntry(PATHS.js);

const common = {
    // Entry accepts a path or an object of entries.
    // We'll be using the latter form given it's
    // convenient with more complex configurations.
    entry: entry,
    output: {
        path: PATHS.build,
        filename: '[name].js',
        //publicPath: PATHS.assets, //这个没啥用
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel', // 'babel-loader' is also a legal name to reference
                query: {
                    presets: ['react', 'es2015']
                }
            },
            //{
            //test: /\.scss$/,
            //loaders: ["style", "css", "sass"],
            //   include: PATHS.views,
            //},
            //{
            //   test: /\.(jpg|png|ttf)$/,
            //   loader: "url?limit=10240&name=fonts/[name][hash].[ext]",
            //   include: PATHS.views,
            //}
        ]
    },
    plugins: []
};


var config; //不区分测试
switch (ENV) {
    //case TEST:
    //	config = merge(
    //		common
    //	);
    //	break;
    case PRO:
        config = merge(
            common,
            uglifyJs()
            //parts.extractBundle({
            //	name: 'vendor',
            //	entries: ['react']
            //})
            //parts.setupCSS(PATHS.app) //不能加多个逗号的哦,我日!
        );
        break;
    default: //开发
        config = merge(
            common
            //setupServer()
            //{
            //	devtool: 'cheap-eval-source-map',
            //},
        );
}

function uglifyJs() {
    return {
        plugins: [
            new webpack.optimize.UglifyJsPlugin({
                compress: {warnings: false},
                sourceMap: false
            })
        ]
    }
}

function setupServer(options) {
    console.log('setupServer');
    options = options || {};
    return {
        devServer: {
            // Enable history API fallback so HTML5 History API based
            // routing works. This is a good default that will come
            // in handy in more complicated setups.
            historyApiFallback: true,
            
            // Unlike the cli flag, this doesn't set
            // HotModuleReplacementPlugin!
            hot: true,
            inline: true,
            
            // Display only errors to reduce the amount of output.
            stats: 'errors-only',
            
            // Parse host and port from env to allow customization.
            //
            // If you use Vagrant or Cloud9, set
            // host: options.host || '0.0.0.0';
            //
            // 0.0.0.0 is available to all network devices
            // unlike default `localhost`.
            host: options.host, // Defaults to `localhost`
            port: options.port || 9000 // Defaults to 8080
        },
        plugins: [
            // Enable multi-pass compilation for enhanced performance
            // in larger projects. Good default.
            new webpack.HotModuleReplacementPlugin({
                multiStep: true
            })
        ]
    };
}

module.exports = config;


